import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

/**
 * 人员定位 mapbox 配置hooks
 *
 * @param {string} Map  实例key
 * @param {string} mapContainerId  容器名称id
 * @param {string} token  token
 * @param {objcet} mapOptions  配置项
 *
 **/
export function useMapbox(mapContainerId, token, mapOptions, Map) {
	console.log("init配置信息", mapboxgl, mapContainerId, token, mapOptions);

	mapboxgl.accessToken = token;
	// 创建地图实例
	const map = new mapboxgl.Map({
		container: mapContainerId,
		...mapOptions
	});

	window[Map] = map;
}

/**
 * @description: 增加图标
 * @param {Array} coordinates 坐标位置 [125.57169452591478, 43.44928196849088]
 * @param {object} icon 相关数据信息
 * @param {string} index 索引/标识
 * @param {string} map 地图实例
 * @param {string} iconSize 图标大小
 * @return {string} 图层id
 * @example: 
 */
export function addPointsIcon(icon, index, map, iconSize) {
	if (!map) return;

	// 加载每个图标
	map.loadImage(icon.url, (error, image) => {
		if (error) throw error;
		if (map.hasImage(icon.name)) {
			map.removeImage(icon.name);
		}
		// 为每个图标添加图像
		map.addImage(icon.name, image);

		// 添加数据源
		if (!map.getSource(`data-source-${index}`)) {
			map.addSource(`data-source-${index}`, {
				type: 'geojson',
				data: {
					type: 'FeatureCollection',
					features: icon.data.map(point => ({
						type: 'Feature',
						geometry: {
							type: 'Point',
							coordinates: point.coordinates
						},
						properties: point.properties
					}))
				}
			});
		}

		// 添加图层
		if (!map.getLayer(`icon-layer-${index}`)) {
			map.addLayer({
				id: `icon-layer-${index}`,
				type: 'symbol',
				source: `data-source-${index}`,
				layout: {
					'icon-image': icon.name,
					'icon-anchor': "bottom",
					'icon-size': iconSize || 0.5
				}
			});
		}
	});
	return `icon-layer-${index}`;
}

/**
 * @description: 清除增加的图标
 * @event: 
 * @param {string} index 索引/标识
 * @param {string}  map 地图实例
 * @return {*}
 * @example: 
 */
export function removePointsIcon(index, map) {
	if (!map) return;

	// 构建图层和数据源的 ID
	const layerId = `icon-layer-${index}`;
	const sourceId = `data-source-${index}`;

	// 移除图层
	if (map.getLayer(layerId)) {
		map.removeLayer(layerId);
	}

	// 移除数据源
	if (map.getSource(sourceId)) {
		map.removeSource(sourceId);
	}
}



/**
 * @description: 更新图标
 * @param {string} points 需要更新的目标icon的id
 * @param {string} icons 需要更新的目标icon
 * @param {string} iconType 图标icon的icon-image标识
 * @param {string} map 地图实例
 * @return {*}
 * @example: 
 */
export function updatePointsIcon(points, icons, iconType, map) {
	if (!map) return;
	let icon = iconType || "custom-icon";
	map.loadImage(icons, function (error, newImage) {
		if (error) throw error;
		// 更新图标
		map.removeImage(icon);
		map.addImage(icon, newImage);

		// 更新图层的图标
		map.getLayer(points) ? map.setLayoutProperty(points, 'icon-image', icon) : console.log("error,无需要更新的图标");
	});
}


/**
 * @description: 增加面
 * @param {string} map 地图实例
 * @param {string} index 索引/唯一标识
 * @param {object} polygon 面的相关数据
 * @return {*}
 * @example: polygon:[
											[
												[125.57169452591478, 43.44928196849088],
												[126.66508970491435, 43.398593506944536],
												[125.883428470566, 44.26451932420093],
												[125.57169452591478, 43.44928196849088],
												// 闭合多边形
											]
										],
 */
export function addMultiplePolygons(map, polygon, index) {
	if (!map) return;

	// 添加数据源
	if (!map.getSource(`polygon-source-${index}`)) {
		map.addSource(`polygon-source-${index}`, {
			type: 'geojson',
			data: {
				type: 'FeatureCollection',
				features: [{
					type: 'Feature',
					geometry: {
						type: 'Polygon',
						coordinates: polygon.coordinates
					},
					properties: polygon.properties
				}]
			}
		});
	}

	// 添加填充图层
	if (!map.getLayer(`polygon-layer-${index}`)) {
		map.addLayer({
			id: `polygon-layer-${index}`,
			type: 'fill',
			source: `polygon-source-${index}`,
			layout: {},
			paint: {
				'fill-color': polygon.color || '#888888',
				'fill-opacity': polygon.opacity || 0.4
			}
		});
	}

	// 添加边框线图层
	if (!map.getLayer(`polygon-border-layer-${index}`)) {
		map.addLayer({
			id: `polygon-border-layer-${index}`,
			type: 'line',
			source: `polygon-source-${index}`,
			layout: {},
			paint: {
				'line-color': polygon.borderColor || '#00CAFF', // 边框线颜色
				'line-width': polygon.borderWidth || 1 // 边框线宽度
			}
		});
	}
}


/**
 * @description: 鼠标悬停效果
 * @param {string} map 地图实例
 * @param {string} points 自定义图标id标识
 * @return {*}
 * @example: 
 */
export function mouse(map, points) {
	if (!map) return;
	map.on('mouseenter', points, () => {
		map.getCanvas().style.cursor = 'pointer';
	});
	map.on('mouseleave', points, () => {
		map.getCanvas().style.cursor = '';
	});
}

/**
 * @description: 相机视角定位
 * @param {object} map 地图实例
 * @param {object} options 视角信息集合
 * @return {*}
 * @example:  options: {
								center: [125.57169452591478, 43.44928196849088],
								zoom: 6.239555123365503,
								pitch: 0,
								bearing: 0,
							}
 */
export function flyTo(map, options) {
	if (!map) return;
	map.flyTo({
		...options
	});
}

/**
 * @description: 调整可视区域范围
 * @event: 调用LngLatBounds，调整地图的视野，以适应一个路线或区域的所有坐标点
 * @param {string} coordinates 坐标 [[128.03499701341036, 43.089967077775924],...,[125.123123,45223123]]
 * @param {object} map 地图实例
 * @param {number} padding 在边界周围添加 100 像素的内边距
 * @return {*}
 * @example: 
 */
export function mapLngLatBounds(map, coordinates, padding) {
	if (!map) return;
	const bounds = coordinates.reduce(function (bounds, coord) {
		return bounds.extend(coord);
	}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

	map.fitBounds(bounds, {
		padding: padding || 100
	});
}

/**
 * @description: 获取图层和调整顺序的方法
 * @event: 
 * @param {string} sourceLayer sourceLayer图层在targetLayer之上
 * @param {string} targetLayer targetLayer图层在sourceLayer之下
 * @return {*}
 * @example: 
 */
export function setLayerOrder(map, sourceLayer, targetLayer) {
	var layers = map.getStyle().layers;
	var sourceIndex = 0;
	var targetIndex = 0;

	// 找到源图层和目标图层的顺序
	for (var i = 0; i < layers.length; i++) {
		if (layers[i].id === sourceLayer) {
			sourceIndex = i;
		} else if (layers[i].id === targetLayer) {
			targetIndex = i;
		}
	}

	// 调整图层顺序
	if (sourceIndex < targetIndex) {
		map.moveLayer(sourceLayer, targetLayer);
	} else {
		map.moveLayer(sourceLayer, targetLayer);
	}
}

/**
 * @description: 溢出所有的点和面
 * @event: 
 * @param {string} map 地图实例
 * @return {*}
 * @example: 
 */
export function removeAllMarkersAndPolygons(map) {
	if (!map) return;

	// 获取地图上的所有图层
	const layers = map.getStyle().layers;

	layers.forEach(layer => {
		if (layer.type === 'symbol' || layer.type === 'fill') {
			// 移除图层
			if (map.getLayer(layer.id)) {
				map.removeLayer(layer.id);
			}

			// 移除数据源
			if (map.getSource(layer.id)) {
				map.removeSource(layer.id);
			}
		}
	});
}
